<template>
  <div class="fly-line-container">
    <Temp title="漫游路径">
      <div class="fly-line">
        <el-tabs
          v-model="activeName"
          @tab-click="onTabClick"
        >
          <el-tab-pane label="系统默认" name="preset">
            <img
              v-if="presetFlyLine.length === 0"
              src="@/assets/img/empty_placeholder.png"
              alt="empty image"
              class="empty-image"
            />
            <el-scrollbar v-else>
              <FlyLineItem
                v-for="(item, index) in presetFlyLine"
                :key="item.id"
                :title="item.name"
                :img="item.img"
                :category="'preset'"
                :index="index"
                @onItemClick="onFlyLineItemClick"
              />
            </el-scrollbar>
          </el-tab-pane>
          <el-tab-pane label="个人录制" name="custom" lazy>
            <div class="custom-content">
              <div
                v-if="customFlyLine.length === 0"
                class="custom-empty"
              >
                <img
                  src="@/assets/img/empty_placeholder.png"
                  alt="empty image"
                  class="empty-image"
                />
              </div>
              <el-scrollbar v-else>
                <FlyLineItem
                  v-for="(item, index) in customFlyLine"
                  :key="item.id"
                  :title="item.name"
                  :img="item.img"
                  :category="'custom'"
                  :index="index"
                  @onItemClick="onFlyLineItemClick"
                  @onEnterDown="onFlyLineItemEnter"
                  @onItemDelete="onFlyLineItemDelete"
                />
              </el-scrollbar>
              <div
                class="add-button"
                @click="onAddButtonClick"
              >
                <i class="el-icon-plus"></i>
                <span>添加漫游路径</span>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </Temp>
    <AddFlyLine
      v-if="showAddFlyLine"
      class="add-fly-line-tool"
    />
  </div>
</template>

<script>
import Temp from '@/components/utool/components/temp'
import FlyLineItem from '@/components/flyLineItem'
import AddFlyLine from '../addFlyLine'
import { getAction } from '@/utils/helper'

// const testPoints = [
//   [117.220356, 31.833959, 0],
//   [117.220361, 31.835111, 0],
//   [117.213242, 31.835863, 0],
//   [117.211926, 31.835738, 0],
//   [117.183103, 31.833906, 0],
//   [117.183136, 31.833586, 0],
//   [117.183968, 31.833637, 0],
//   [117.184038, 31.833134, 0],
//   [117.184364, 31.833142, 0],
//   [117.184519, 31.833375, 0]
// ]

let mapViewer = null

let flyManager = null

let routeCollection = null

export default {
  inject: ['viewerId'],
  components: {
    Temp,
    FlyLineItem,
    AddFlyLine
  },
  data() {
    return {
      showAddFlyLine: false,
      activeName: 'preset',
      presetFlyLine: [],
      customFlyLine: []
    }
  },
  async created() {
    const { viewer } = await getAction(this.viewerId)
    mapViewer = viewer
    mapViewer.scene.globe.depthTestAgainstTerrain = false

    routeCollection = new Cesium.RouteCollection(
      mapViewer.entities
    )
    flyManager = new Cesium.FlyManager({
      scene: mapViewer.scene,
      routes: routeCollection
    })

    this.fetchPresetFlyLine()
  },
  mounted() {
    this.$bus.$on('flyLineProceed', () => {
      this.startFly()
    })
    this.$bus.$on('flyLinePause', () => {
      if (flyManager) {
        flyManager.pause()
      }
    })
    this.$bus.$on('flyLineStop', () => {
      document.removeEventListener('keyup', this.keyEvent)
      this.stopFly()
    })

    this.$bus.$on('showAddFlyLine', () => {
      this.showAddFlyLine = true
    })
    this.$bus.$on('hideAddFlyLine', () => {
      this.showAddFlyLine = false
    })
    this.$bus.$on('haveAddedCustomFlyLine', () => {
      this.getLocalCustomFlyLineData()
    })
  },
  beforeDestroy() {
    document.removeEventListener('keyup', this.keyEvent)
    this.$bus.$emit('flyLineStop')
    if (flyManager) {
      flyManager.stop()
      const route = flyManager.currentRoute
      flyManager = null
      if (route) {
        route.isLineVisible = false
        route.isStopVisible = false
        route.clear()
      }
    }
  },
  methods: {
    onTabClick(tab) {
      if (tab.name === 'preset') {
        this.$bus.$emit('hideAddFlyLine')
        if (this.presetFlyLine.length === 0) {
          this.fetchPresetFlyLine()
        }
      } else if (
        tab.name === 'custom' &&
        this.customFlyLine.length === 0
      ) {
        this.fetchCustomFlyLine()
      }
    },
    /**
     * 获取系统默认漫游路径
     */
    fetchPresetFlyLine() {
      // setTimeout(() => {
      //   this.presetFlyLine.push(...[
      //     {
      //       id: '1',
      //       name: '漫游路径1',
      //       img: 'https://cube.elemecdn.com/6/94/4d3ea53c084bad6931a56d5158a48jpeg.jpeg',
      //       points: testPoints
      //     },
      //     {
      //       id: '2',
      //       name: '漫游路径2',
      //       img: 'https://cube.elemecdn.com/6/94/4d3ea53c084bad6931a56d5158a48jpeg.jpeg',
      //       points: testPoints
      //     },
      //     {
      //       id: '3',
      //       name: '漫游路径3',
      //       img: 'https://cube.elemecdn.com/6/94/4d3ea53c084bad6931a56d5158a48jpeg.jpeg',
      //       points: testPoints
      //     },
      //     {
      //       id: '4',
      //       name: '漫游路径4',
      //       points: testPoints
      //     },
      //     {
      //       id: '5',
      //       name: '漫游路径5',
      //       img: 'https://cube.elemecdn.com/6/94/4d3ea53c084bad6931a56d5158a48jpeg.jpeg',
      //       points: testPoints
      //     },
      //     {
      //       id: '6',
      //       name: '漫游路径6',
      //       img: 'https://cube.elemecdn.com/6/94/4d3ea53c084bad6931a56d5158a48jpeg.jpeg',
      //       points: testPoints
      //     }
      //   ])
      // }, 100)
    },
    /**
     * 获取个人录制漫游路径
     */
    fetchCustomFlyLine() {
      setTimeout(() => {
        this.getLocalCustomFlyLineData()
      }, 500)
    },
    getLocalCustomFlyLineData() {
      const localCustomFlyLineData =
        window.localStorage.getItem('customFlyLineData')
      if (localCustomFlyLineData) {
        const list = JSON.parse(localCustomFlyLineData)
        if (Array.isArray(list)) {
          this.customFlyLine = list
        }
      }
    },
    /**
     * 漫游路径点击事件
     */
    onFlyLineItemClick(category, index) {
      document.removeEventListener('keyup', this.keyEvent)
      this.stopFly()
      // let id = ''
      // let name = ''
      let data = ''
      if (category === 'preset') {
        // id = this.presetFlyLine[index].id
        // name = this.presetFlyLine[index].name
        data = this.presetFlyLine[index].data
      } else {
        // id = this.customFlyLine[index].id
        // name = this.customFlyLine[index].name
        data = this.customFlyLine[index].data
      }
      routeCollection.readyPromise.then(() => {
        this.$bus.$emit('flyLineStart')
        flyManager.routes = routeCollection
        const route = flyManager.currentRoute
        const entities = Array.from(
          route.stopCollection.map((item) => item.point)
        )
        mapViewer.camera.flyTo({
          destination:
            Cesium.Rectangle.fromCartesianArray(entities)
        })
        route.isLineVisible = true
        route.isStopVisible = true
        // this.startFly()
      })
      routeCollection.fromXML(data)
    },
    onFlyLineItemEnter(category, index, title) {
      if (category === 'custom') {
        this.customFlyLine[index].name = title
        window.localStorage.setItem(
          'customFlyLineData',
          JSON.stringify(this.customFlyLine)
        )
      }
    },
    onFlyLineItemDelete(category, index) {
      if (category === 'custom') {
        this.$confirm('是否删除该漫游路线？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            this.customFlyLine.splice(index, 1)
            window.localStorage.setItem(
              'customFlyLineData',
              JSON.stringify(this.customFlyLine)
            )
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          })
          .catch(() => {})
      }
    },
    keyEvent(e) {
      console.log(e)
      if (e.code === 'Escape') {
        this.$confirm('是否退出漫游？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            document.removeEventListener(
              'keyup',
              this.keyEvent
            )
            this.$bus.$emit('flyLineStop')
          })
          .catch(() => {})
      }
    },
    startFly() {
      document.addEventListener('keyup', this.keyEvent)
      if (flyManager) {
        flyManager.play()
      }
    },
    stopFly() {
      if (flyManager) {
        flyManager.stop()
        const route = flyManager.currentRoute
        if (route) {
          route.isLineVisible = false
          route.isStopVisible = false
          route.clear()
        }
        routeCollection = new Cesium.RouteCollection(
          mapViewer.entities
        )
        // flyLine.destroy()
        // flyLine = null
      }
    },
    onAddButtonClick() {
      this.$bus.$emit('flyLineStop')
      this.$bus.$emit('showAddFlyLine')
    }
  }
}
</script>

<style lang="scss">
.fly-line-container {
  display: flex;
  flex-direction: row-reverse;
  align-items: flex-end;

  .fly-line {
    height: 331px;
    display: flex;
    flex-direction: column;
    align-items: center;
    background-color: #193b51;
    border-radius: 0 0 8px 8px;

    .el-tabs {
      height: 100%;
      padding: 0 16px;
      margin: 0;
      display: flex;
      flex-direction: column;

      .el-tabs__item {
        color: #d2e6f0;
        padding: 0 0 0 6px;
      }

      .el-tabs__item:first-of-type {
        padding-left: 0;
      }

      .el-tabs__item.is-active {
        color: #00d2ff;
      }

      .el-tabs__active-bar {
        background-color: #00d2ff;
      }

      .el-tabs__nav {
        background-color: #193b51;
      }

      .el-tabs__content {
        width: 100%;
        height: 100%;
        padding-bottom: 10px;

        .el-tab-pane {
          height: 100%;
          width: 100%;
          display: flex;
          flex-direction: column;
          align-items: center;

          .custom-empty {
            width: 100%;
            height: 100%;
            display: flex;
            flex-direction: column;
            justify-content: space-between;
            align-items: center;
          }

          .el-scrollbar {
            flex: 1;
            height: 100%;
            width: 100%;

            .el-scrollbar__wrap {
              overflow-x: hidden;

              .el-scrollbar__view {
                padding: 0 10px;
                display: flex;
                flex-direction: column;
                align-items: center;
              }

              .fly-line-item {
                width: 100%;
                margin-bottom: 14px;
              }

              .fly-line-item:last-of-type {
                margin-bottom: 0;
              }
            }
          }
        }
      }
    }
  }

  .add-fly-line-tool {
    width: 250px;
    margin-right: 10px;
  }
}

.custom-content {
  display: flex;
  flex-direction: column;
  flex: 1;
  width: 100%;
  height: 100%;

  .add-button {
    margin-top: 10px;
  }
}

.empty-image {
  width: 55px;
  margin-top: 20px;
}

.add-button {
  width: 100%;
  background-color: #0c87a8;
  color: #fff;
  display: flex;
  justify-content: center;
  padding: 8px 0;
  align-items: center;
  border-radius: 2px;
  cursor: pointer;

  i {
    font-weight: 800;
    margin-right: 2px;
  }

  span {
    font-size: 14px;
  }
}
</style>
